import {app, BrowserWindow, ipcMain, ipcRenderer} from 'electron';
import path from 'path';
import os from 'os';
import { fileURLToPath } from 'url'
import {initialize,enable} from "@electron/remote/main/index.js";
import { Channel } from './channel/channel'

// needed in case process is undefined under Linux
const platform = process.platform || os.platform();
const mainStorage = {
  aaa:1
}
const currentDir = fileURLToPath(new URL('.', import.meta.url));

let mainWindow: BrowserWindow | undefined;
let callingWindow: BrowserWindow | undefined;
export let windowAll = {
  get mainWindow() { return mainWindow; },
  get callingWindow() { return callingWindow; }
}
initialize();

//打开主窗体
async function createWindow() {
  /**
   * Initial window options
   */
  console.log('currentDir',currentDir)
  mainWindow = new BrowserWindow({
    icon: path.resolve(currentDir, 'icons/icon.png'), // tray icon
    width: 1450,
    height: 800,
    useContentSize: true,
    frame: false,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      // enableRemoteModule: true,
      // More info: https://v2.quasar.dev/quasar-cli-vite/developing-electron-apps/electron-preload-script
      preload: path.resolve(
        currentDir,
        path.join(process.env.QUASAR_ELECTRON_PRELOAD_FOLDER, 'electron-preload' + process.env.QUASAR_ELECTRON_PRELOAD_EXTENSION)
      ),
    },
  });

  enable(mainWindow.webContents)

  if (process.env.DEV) {
    await mainWindow.loadURL(process.env.APP_URL);
  } else {
    await mainWindow.loadFile('index.html');
  }

  if (process.env.DEBUGGING) {
    // if on DEV or Production with debug enabled
    mainWindow.webContents.openDevTools();
  } else {
    // we're on production; no access to devtools pls
    mainWindow.webContents.on('devtools-opened', () => {
      mainWindow?.webContents.closeDevTools();
    });
  }

  mainWindow.on('closed', () => {
    mainWindow = undefined;
  });
}
//打开副窗体
export async function createCallingWindow() {
  if (!mainWindow) return; // 确保父窗口存在
  if (callingWindow) {
    callingWindow.focus();
    return;
  }

  callingWindow = new BrowserWindow({
    width: 1600,
    height: 800,
    minWidth: 1400,      // 最小宽度
    minHeight: 800,     // 最小高度
    useContentSize: true,
    frame: false,
    show: false,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      preload: path.resolve(
        path.join(process.env.QUASAR_ELECTRON_PRELOAD_FOLDER, 'electron-preload' + process.env.QUASAR_ELECTRON_PRELOAD_EXTENSION)
      ),
    },
  });

  enable(callingWindow.webContents);

  if (process.env.DEV) {
    await callingWindow.loadURL(process.env.APP_URL + '#/calling');
  } else {
    await callingWindow.loadFile('index.html', { hash: '/calling' });
  }

  callingWindow?.show();

  if (process.env.DEBUGGING) {
    callingWindow.webContents.openDevTools();
  } else {
    callingWindow.webContents.on('devtools-opened', () => {
      callingWindow?.webContents.closeDevTools();
    });
  }

  callingWindow.on('closed', () => {
    callingWindow = undefined;
  });
}

void app.whenReady().then(()=>{

  let channelObject:any = new Channel(windowAll);

  ipcMain.on('openCallingWindow', (_,url) => {
    createCallingWindow();
  });

// 处理渲染进程的请求并返回值
  ipcMain.handle('getSysStorage', async (event, a, b) => {
    // 返回值给渲染进程
    return mainStorage; // 等价于 return Promise.resolve(result)
  });

  Object.getOwnPropertyNames(Object.getPrototypeOf(channelObject))
    .forEach((c:string) => {
      ipcMain.on(c, (event, ...args) => {
        console.log('main-args：',...args);
        return channelObject[c](...args);
      });
    })

  createWindow()
});

app.on('window-all-closed', () => {
  if (platform !== 'darwin') {
    app.quit();
  }
});


app.on('activate', () => {
  if (mainWindow === undefined) {
    void createWindow();
  }
});
